package ui.operator;

import ent.Operator;
import ent.ViewPanel;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import util.SuperView;

/**
 *
 * @author t
 */
public class PermissionView extends SuperView {

    private static PermissionView instance = new PermissionView();

    public static void display() {
        instance.setVisible(true);
    }

    public static PermissionView getInstance() {
        return instance;
    }

    public PermissionView() {
        onLoad();
    }

    /**
     * Creates new form CustomerView
     */
    public PermissionView(java.awt.Frame parent, boolean modal) {
        this();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        operatorList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        permitedViewList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        assignButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        availableViewList = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        removeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("PERMISSION MANAGEMENT");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel1.setText("Operator:");

        operatorList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                operatorListMouseClicked(evt);
            }
        });
        operatorList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                operatorListKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(operatorList);

        jScrollPane2.setViewportView(permitedViewList);

        jLabel2.setText("Permited:");

        assignButton.setText("<< Assign");
        assignButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                assignButtonActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(availableViewList);

        jLabel3.setText("Available:");

        removeButton.setText("Remove >>");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                                .addComponent(jLabel1))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(assignButton)
                            .addComponent(removeButton)))
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {assignButton, removeButton});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2, jScrollPane3});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(assignButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(removeButton))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void operatorListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_operatorListMouseClicked
        loadOperatorViews();
        loadAvaliableViews();
}//GEN-LAST:event_operatorListMouseClicked

    private void operatorListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_operatorListKeyReleased
        loadOperatorViews();
        loadAvaliableViews();
}//GEN-LAST:event_operatorListKeyReleased

    private void assignButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_assignButtonActionPerformed
        try {
            Operator operator = (Operator) operatorList.getSelectedValue();
            if (operator == null) {
                return;
            }
            Object[] objects = availableViewList.getSelectedValues();
            List<Serializable> ses = new ArrayList<Serializable>();
            for (Object object : objects) {
                ViewPanel viewPanel = (ViewPanel) object;
                viewPanel.getOperatorCollection().add(operator);
                operator.getViewPanelCollection().add(viewPanel);
                ses.add(viewPanel);
            }
            ses.add(operator);
            m.update(ses);
            m.clearCache();
            loadOperatorViews();
            loadAvaliableViews();

        } catch (NullPointerException e) {
            showError("Pleace Sellect values");
        }
    }//GEN-LAST:event_assignButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        removePermission();
    }//GEN-LAST:event_removeButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PermissionView dialog = new PermissionView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton assignButton;
    private javax.swing.JList availableViewList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList operatorList;
    private javax.swing.JList permitedViewList;
    private javax.swing.JButton removeButton;
    // End of variables declaration//GEN-END:variables

    private void loadAvaliableViews() {
        Object o = operatorList.getSelectedValue();
        if (o == null) {
            return;
        }
        Operator operator = (Operator) o;
        operator = m.find(Operator.class, operator.getUsername());
        List<ViewPanel> viewPanels = m.exNamedQueryResult("ViewPanel.findAll");
        List<ViewPanel> blankViewPanels = new ArrayList<ViewPanel>();

        if (operator == null || viewPanels == null) {
            availableViewList.setListData(blankViewPanels.toArray());
            return;
        }

        for (Iterator<ViewPanel> it = viewPanels.iterator(); it.hasNext();) {
            ViewPanel viewPanel = it.next();
            Collection<Operator> operators = viewPanel.getOperatorCollection();
            if (operators.isEmpty()) {
                blankViewPanels.add(viewPanel);
            } else if (!operators.contains(operator)) {
                blankViewPanels.add(viewPanel);
            }
        }
        availableViewList.setListData(blankViewPanels.toArray());
    }

    private void loadOperatorViews() {
        Object o = operatorList.getSelectedValue();
        if (o == null) {
            return;
        }
        Operator operator = (Operator) o;
        operator = m.find(Operator.class, operator.getUsername());
        permitedViewList.setListData(operator.getViewPanelCollection().toArray());
    }

    public void removePermission() {
        Object o = operatorList.getSelectedValue();
        if (o == null) {
            return;
        }
        Operator operator = (Operator) o;
        o = permitedViewList.getSelectedValue();
        if (o == null) {
            return;
        }
        ViewPanel viewPanel = (ViewPanel) o;
        viewPanel.getOperatorCollection().remove(operator);
        operator.getViewPanelCollection().remove(viewPanel);
        m.update(viewPanel);
        m.update(operator);

        loadAvaliableViews();
        loadOperatorViews();
    }

    protected void onLoad() {
        initComponents();
        refresh();
    }

    private void refresh() {
        loadOperators();
        loadAvaliableViews();
        loadOperatorViews();
    }

    private void loadOperators() {
        List<Operator> operators = m.find(Operator.class);
        operatorList.setListData(operators.toArray());
    }
}
